package com.simon.nio.test2;

import com.simon.nio.CharsetHelper;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * Created by changf on 2017/7/13.
 */
public class NioClient {


    public static void main(String[] args) throws Exception{
        NioClient client=new NioClient();
        client.init();
    }
    public void init() throws Exception {
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        socketChannel.connect(new InetSocketAddress("localhost",8989));
        Selector selector = Selector.open();
        socketChannel.register(selector, SelectionKey.OP_CONNECT);



        boolean flag = true;
        while (flag) {

            selector.select();
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            System.out.println("===============");
            while (iterator.hasNext()) {
                System.out.println("client start...");
                SelectionKey key = iterator.next();
                iterator.remove();
                if (key.isConnectable()) {
                    if (socketChannel.isConnectionPending()) {
                        if (socketChannel.finishConnect()) {
                            key.interestOps(SelectionKey.OP_READ);
                            socketChannel.write(CharsetHelper.encode(CharBuffer.wrap("hello")));
                            Thread.sleep(2000);

                        } else {
                            key.cancel();
                        }

                    }


                } else if (key.isReadable()) {
                    socketChannel = (SocketChannel) key.channel();
                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                    socketChannel.read(byteBuffer);
                    byteBuffer.flip();
                    CharBuffer decode = CharsetHelper.decode(byteBuffer);
                    System.out.println("get response:" + decode.toString());
                    flag=false;


                }


            }


        }
        socketChannel.close();
        selector.close();
        System.out.println("client end");
    }
}
